package com.kongzue.baseokhttpv3.slice;


import com.kongzue.baseokhttp.BaseWebSocket;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.Logger;
import com.kongzue.baseokhttp.listener.*;
import com.kongzue.baseokhttp.util.*;
import com.kongzue.baseokhttpv3.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Point;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import okhttp3.Response;
import okio.ByteString;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


public class MainAbility1Slice extends AbilitySlice {
    Text tv_request_code;

    Text tv_result_http;

    Text tv_result_cookie;

    Text tv_result_header;

    Button btn_http;

    Button btn_http_ssl;

    Button btn_http_clean;

    Button btn_set_cookie;

    Button btn_get_cookie;

    Button btn_set_header;

    Button btn_get_header;

    ListContainer listView;

    Button btn_download;

    Button btn_download_cancel;

    ProgressBar psg_download;

    ProgressBar psg_upload;

    Button btn_connect;

    Button btn_disconnect;

    Text result_websocket;

    BaseWebSocket baseWebSocket;

    Button btn_send;

    TextField edit_send;

    LoadDialog loadDialog;

    Button btn_upload;

    public static final int CODE = 200;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        tv_request_code = (Text) findComponentById(ResourceTable.Id_tv_request_code);
        tv_result_http = (Text) findComponentById(ResourceTable.Id_tv_result_http);
        tv_result_cookie = (Text) findComponentById(ResourceTable.Id_tv_result_cookie);
        tv_result_header = (Text) findComponentById(ResourceTable.Id_tv_result_header);
        listView = (ListContainer) findComponentById(ResourceTable.Id_listView);
        btn_download = (Button) findComponentById(ResourceTable.Id_btn_download);
        btn_download_cancel = (Button) findComponentById(ResourceTable.Id_btn_download_cancel);
        psg_download = (ProgressBar) findComponentById(ResourceTable.Id_psg_download);
        psg_upload = (ProgressBar) findComponentById(ResourceTable.Id_psg_upload);
        btn_connect = (Button) findComponentById(ResourceTable.Id_btn_connect);
        btn_disconnect = (Button) findComponentById(ResourceTable.Id_btn_disconnect);
        btn_send = (Button) findComponentById(ResourceTable.Id_btn_send);
        edit_send = (TextField) findComponentById(ResourceTable.Id_edit_send);
        result_websocket = (Text) findComponentById(ResourceTable.Id_result_websocket);
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(
                this.getContext());
        Point pt = new Point();
        display.get().getSize(pt);

        tv_request_code.setWidth((int) (pt.position[0] * 1.4));
        tv_request_code.setText(
                "HttpRequest.POST(context,  \"https://www.apiopen.top/femaleNameApi\",  new  Parameter()\n                                .add(\"page\",  \"1\")\n                ,  new  ResponseListener()  {\n                        @Override\n                        public  void  onResponse(String  response,  Exception  error)  {\n                                if  (error  ==  null)  {\n                                        resultHttp.setText(response);\n                                }  else  {\n                                        Toast.makeText(me,  \"请求失败\",  Toast.LENGTH_SHORT);\n                                }\n                        }\n                });\"\n");
        btn_http = (Button) findComponentById(ResourceTable.Id_btn_http);
        btn_http_ssl = (Button) findComponentById(ResourceTable.Id_btn_http_ssl);
        btn_http_clean = (Button) findComponentById(ResourceTable.Id_btn_http_clean);
        btn_set_cookie = (Button) findComponentById(ResourceTable.Id_btn_set_cookie);
        btn_get_cookie = (Button) findComponentById(ResourceTable.Id_btn_get_cookie);
        btn_set_header = (Button) findComponentById(ResourceTable.Id_btn_set_header);
        btn_get_header = (Button) findComponentById(ResourceTable.Id_btn_get_header);
        btn_upload = (Button) findComponentById(ResourceTable.Id_btn_upload);

        BaseOkHttpConfig.getInstance().setOverallHeader(new Parameter().add("Charset", "UTF-8").add("Content-Type",
                "application/json").add("Accept-Encoding", "gzip,deflate"));
        BaseOkHttpConfig.getInstance().setParameterInterceptListener(new ParameterInterceptListener<JsonMap>() {
            @Override
            public JsonMap onIntercept(Context context, String url, JsonMap o) {
                return null;
            }
        });
        BaseOkHttpConfig.getInstance().setResponseInterceptListener(new ResponseInterceptListener() {
            @Override
            public boolean onResponse(Context context, String url, String response,
                                      Exception error) {
                if (error != null) {
                    return true;
                } else {
                    return true;
                }
            }
        });
        JsonMapConfig.getInstance().setPreParsing(true);
        final Context context = this;

        loadDialog = new LoadDialog(this);
        btn_http.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                BaseOkHttpConfig.getInstance().setSSLInAssetsFileName(null);
                loadDialog.show();
                HttpRequest.POST(MainAbility1Slice.this, "/getWangYiNews",
                        new Parameter().add("page", "1").add("count", 5), new JsonResponseListener() {
                            @Override
                            public void onResponse(JsonMap main, Exception error) {
                                loadDialog.remove();
                                if (error == null) {
                                    HiLog.info(Logger.LABEL,
                                            "请求成功" + main.getList("result").toString());
                                    tv_result_http.setText(main.toString());
                                    JsonList dataList = main.getList("result");
                                    //
                                    listView.setItemProvider(
                                            new ListAdapter(MainAbility1Slice.this, dataList));
                                    //
                                } else {
                                    tv_result_http.setText("请求失败");
                                    HiLog.info(Logger.LABEL, "请求超时".toString());
                                    ToastDialog toastDialog = new ToastDialog(MainAbility1Slice.this);
                                    toastDialog.setText("time out").setDuration(1000).show();
                                }
                            }
                        });

            }
        });

        btn_http_ssl.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                loadDialog.show();
                BaseOkHttpConfig.getInstance().setSSLInAssetsFileName("test.cer");
                HttpRequest.POST(MainAbility1Slice.this, "/getWangYiNews",
                        new Parameter().add("page", "1").add("count", 5), new JsonResponseListener() {
                            @Override
                            public void onResponse(JsonMap main, Exception error) {
                                loadDialog.remove();
                                if (error == null) {
                                    HiLog.info(Logger.LABEL,
                                            "请求成功" + main.getList("result").toString());
                                    tv_result_http.setText(main.toString());
                                    JsonList dataList = main.getList("result");
                                    listView.setItemProvider(
                                            new ListAdapter(MainAbility1Slice.this, dataList));
                                } else {
                                    tv_result_http.setText("请求失败");
                                    HiLog.info(Logger.LABEL, "请求超时".toString());
                                    ToastDialog toastDialog = new ToastDialog(MainAbility1Slice.this);
                                    toastDialog.setText("time out").setDuration(1000).show();
                                }
                            }
                        });
            }
        });

        btn_http_clean.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                listView.setItemProvider(new ListAdapter(MainAbility1Slice.this, new JsonList()));
                tv_result_http.setText("");
            }
        });
        TextField url = (TextField) findComponentById(ResourceTable.Id_url_download);
        //配置下载地址url
        url.setText("https://s9.pstatp.com/package/apk/lark/1583_40155/lark_feishu_website_organic_and_v1583_40155_9f99_1622703997.apk");
        btn_download.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                btn_download.setEnabled(false);
                btn_download_cancel.setEnabled(true);
                btn_download_cancel.setAlpha(1f);
                btn_download.setAlpha(0.5f);
                httpRequest = HttpRequest.build(context,
                        url.getText().toString());
                psg_download.setProgressValue(0);
                String filePath = url.getText().trim();
                if (TextTool.isNullOrEmpty(filePath)) {
                    ToastDialog toastDialog = new ToastDialog(MainAbility1Slice.this);
                    toastDialog.setText("file path empty").setDuration(1000).show();
                    return;
                }
                httpRequest.doDownload(
                        new File(context.getExternalFilesDir("ceshi"), filePath.substring(url.getText().trim().lastIndexOf("/"))),
                        new OnDownloadListener() {
                            @Override
                            public boolean onDownLoadCheck(Response response) {
                                long total = response.body().contentLength();
                                //文件下载失败
                                if (total < 0 || response.code() != CODE) {

                                    return false;
                                }
                                return true;
                            }

                            @Override
                            public void onDownloadSuccess(File file) {
                                psg_download.setProgressValue(100);
                                ToastDialog toastDialog = new ToastDialog(MainAbility1Slice.this);
                                toastDialog.setText("ok").setDuration(1000).show();
                                HiLog.info(Logger.LABEL, "文件已下载完成");
                            }

                            @Override
                            public void onDownloading(int progress) {
                                psg_download.setProgressValue(progress);
                                HiLog.info(Logger.LABEL, "进度" + progress);
                            }

                            @Override
                            public void onDownloadFailed(Exception e) {
                                if(e instanceof SocketException){
                                    HiLog.info(Logger.LABEL, "下载取消" + e.toString());
                                    ToastDialog toastDialog = new ToastDialog(MainAbility1Slice.this);
                                    toastDialog.setText("cancel").setDuration(1000).show();
                                }else{
                                    HiLog.info(Logger.LABEL, "下载失败" + e.toString());
                                    ToastDialog toastDialog = new ToastDialog(MainAbility1Slice.this);
                                    toastDialog.setText("err").setDuration(1000).show();
                                }
                            }
                        });
            }

        });

        btn_download_cancel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                btn_download.setEnabled(true);
                btn_download.setAlpha(1f);
                btn_download_cancel.setEnabled(false);
                btn_download_cancel.setAlpha(0.5f);
                httpRequest.stop();
            }
        });

        edit_send.setEnabled(false);
        btn_send.setEnabled(false);
        //配置WebSocket的url
        btn_connect.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                result_websocket.setText("开始连接...");
                btn_connect.setEnabled(false);
                baseWebSocket = BaseWebSocket.BUILD(context,
                        "wss://echo.websocket.org").setWebSocketStatusListener(
                        new WebSocketStatusListener() {

                            @Override
                            public void connected(Response response) {
                                result_websocket.setText("Connected");
                                btn_disconnect.setEnabled(true);
                                btn_disconnect.setAlpha(1f);
                                btn_connect.setEnabled(false);
                                btn_connect.setAlpha(0.5f);
                                edit_send.setEnabled(true);
                                btn_send.setEnabled(true);
                                btn_send.setAlpha(1f);
                            }

                            @Override
                            public void onMessage(String message) {
                                result_websocket.setText("onMessage：" + message);
                            }

                            @Override
                            public void onMessage(ByteString message) {

                            }


                            @Override
                            public void onReconnect() {
                                result_websocket.setText("Reconnect");
                                btn_disconnect.setEnabled(true);
                                btn_disconnect.setAlpha(1f);
                                btn_connect.setEnabled(false);
                                btn_connect.setAlpha(0.5f);
                                edit_send.setEnabled(false);
                                btn_send.setEnabled(false);
                                btn_send.setAlpha(0.5f);
                            }

                            @Override
                            public void onDisconnected(int breakStatus) {
                                result_websocket.setText("Disconnected");
                                btn_disconnect.setEnabled(false);
                                btn_disconnect.setAlpha(0.5f);
                                btn_connect.setEnabled(true);
                                btn_connect.setAlpha(1f);
                                edit_send.setEnabled(false);
                                btn_send.setEnabled(false);
                                btn_send.setAlpha(0.5f);
                            }

                            @Override
                            public void onConnectionFailed(Throwable t) {
                                result_websocket.setText("ConnectionFailed");
                                btn_disconnect.setEnabled(false);
                                btn_disconnect.setAlpha(0.5f);
                                btn_connect.setEnabled(true);
                                btn_connect.setAlpha(1f);
                                edit_send.setEnabled(false);
                                btn_send.setEnabled(false);
                                btn_send.setAlpha(0.5f);
                                t.printStackTrace();
                            }
                        }).startConnect();
            }
        });

        btn_send.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String s = edit_send.getText().trim();
                if (!s.isEmpty()) {
                    if (baseWebSocket != null) baseWebSocket.send(s);
                }
            }
        });

        btn_disconnect.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (baseWebSocket != null) baseWebSocket.disConnect();
            }
        });

        btn_set_header.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                BaseOkHttpConfig.getInstance().setOverallHeader(new Parameter().add("Charset", "UTF-8").add(
                        "Content-Type", "application/json").add("Accept-Encoding", "gzip,deflate").add(
                        "testKey", "testValues"));
            }
        });

        btn_get_header.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                tv_result_header.setText(BaseOkHttpConfig.getInstance().getOverallHeader().toParameterString());
            }
        });

        btn_set_cookie.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (httpRequest != null) {
                    httpRequest.setCookie("test");
                }
            }
        });

        btn_get_cookie.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (httpRequest != null) {
                    tv_result_cookie.setText(httpRequest.getCookie());
                }
            }
        });

        btn_upload.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                ResourceManager resManager = getResourceManager();
                RawFileEntry rawFileEntry = resManager.getRawFileEntry(
                        "resources/rawfile/70810b0e1dbeb842c3b45dc007988737.jpeg");

                byte[] buffer;
                try {
                    buffer = new byte[rawFileEntry.openRawFile().available()];
                    rawFileEntry.openRawFile().read(buffer);
                    File targetFile = new File(getFilesDir().getPath() + "/test.jpeg");
                    OutputStream outStream = new FileOutputStream(targetFile);
                    outStream.write(buffer);

                    List<File> fileList = new ArrayList<File>();
                    fileList.add(targetFile);
                    HttpRequest.build(context,
                            "https://hn216.api.yesapi.cn/?s=App.CDN.UploadImg").addHeaders("Charset",
                            "UTF-8").addParameter("return_data", "0").addParameter("app_key",
                            "DC43EBA4682FE70A316898472E5A0D2F").addParameter("sign",
                            "7BDB268AEED6EF49B0B027B8CCDE5EC8").addParameter("file",
                            fileList).setUploadProgressListener(
                            new UploadProgressListener() {
                                @Override
                                public void onUpload(float percentage,
                                                     long current, long total,
                                                     boolean done) {
                                    if (done) {
                                        ToastDialog toastDialog = new ToastDialog(MainAbility1Slice.this);
                                        toastDialog.setText("ok").setDuration(1000).show();
                                    }
                                    psg_upload.setProgressValue(
                                            (int) (current / (total * 1.0f) * 100));
                                }
                            }).doPost();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private HttpRequest httpRequest;

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
